package cn.iocoder.yudao.module.service.service.message;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.service.controller.admin.message.vo.ServiceMessagePageReqVO;
import cn.iocoder.yudao.module.service.controller.admin.message.vo.ServiceMessageSaveReqVO;
import cn.iocoder.yudao.module.service.dal.dataobject.message.ServiceMessageDO;
import cn.iocoder.yudao.module.service.dal.mysql.message.ServiceMessageMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.service.enums.ErrorCodeConstants.MESSAGE_NOT_EXISTS;

/**
 * 对话消息 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class ServiceMessageServiceImpl implements ServiceMessageService {

    @Resource
    private ServiceMessageMapper messageMapper;

    @Override
    public Long createMessage(ServiceMessageSaveReqVO createReqVO) {
        // 插入
        ServiceMessageDO message = BeanUtils.toBean(createReqVO, ServiceMessageDO.class);
        messageMapper.insert(message);
        // 返回
        return message.getId();
    }

    @Override
    public Long createMessage(ServiceMessageDO createDO) {
        messageMapper.insert(createDO);
        // 返回
        return createDO.getId();
    }

    @Override
    public void updateMessage(ServiceMessageSaveReqVO updateReqVO) {
        // 校验存在
        validateMessageExists(updateReqVO.getId());
        // 更新
        ServiceMessageDO updateObj = BeanUtils.toBean(updateReqVO, ServiceMessageDO.class);
        messageMapper.updateById(updateObj);
    }

    @Override
    public void deleteMessage(Long id) {
        // 校验存在
        validateMessageExists(id);
        // 删除
        messageMapper.deleteById(id);
    }

    private void validateMessageExists(Long id) {
        if (messageMapper.selectById(id) == null) {
            throw exception(MESSAGE_NOT_EXISTS);
        }
    }

    @Override
    public ServiceMessageDO getMessage(Long id) {
        return messageMapper.selectById(id);
    }

    @Override
    public PageResult<ServiceMessageDO> getMessagePage(ServiceMessagePageReqVO pageReqVO) {
        return messageMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ServiceMessageDO> getMessageList(Long customerId) {
        return messageMapper.selectList(new LambdaQueryWrapperX<ServiceMessageDO>()
                .eq(ServiceMessageDO::getFromUserId, customerId)
                .or()
                .eq(ServiceMessageDO::getToUserId, customerId)
        );
//        return null;
    }
}